"""
    Des: start test UI
    Modified: 2022-1-31
"""
import tkinter as tk
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.scrolled import ScrolledFrame
# import tk_button as tkButton
from functools import partial
# import json

from pykeyboard import PyKeyboard	# 模拟键盘
from pathlib import Path
import sys
import os
# sys.path.append(os.getcwd())
sys.path.append(str(Path(__file__).parent.parent))
import Sequence.main as Main
import stationConfig 
from threading import Thread, current_thread
from Log.outputLog import Log  as log
from Utils.varStationConfig import VarStationConfig as varConfig

class DataEntryForm(ttk.Frame):

    # PATH = Path(__file__).parent / 'assets'

    def __init__(self, master,isAuditMode,groupName,tableTree,dataArray,groupArray,resultArray,selectIndex,cbo):


        super().__init__(master, padding=(10, 5))
        self.tableTree = tableTree

        self.dataArray = dataArray
        self.groupArray = groupArray
        self.resultArray = resultArray

        self.selectIndex = selectIndex
        self.cbo = cbo

        self.pack(fill=BOTH, expand=YES)
        # 定义实例
        self.keyboard = PyKeyboard()
        self.table = None
        if isAuditMode:
            print("this is audit mode")
        else:
            print("this is production mode")
        # form variables
        self.snTable = []
        for i in range(0,10):
            self.snTable.insert(i,ttk.StringVar(value=""))
            # self.snTable.insert(i,'')
            # self.snTable = ttk.StringVar(value="")
        # self.sn = ttk.StringVar(value="")

        config = stationConfig.stationConfig()
        self.count = config.GroupCount
        # for i in range(1,count):
        #     thread = Thread(target=self.startTest, args=str(i), name=i)
        #     thread.setDaemon(True)
        #     thread.start() 
        try:
            isSNInput = config.SNInput
            print("snsnsn:",isSNInput)
            if isSNInput == 1 :#扫码框
                self.create_form_entry(groupName, self.snTable)
            elif isSNInput == 2 :#按钮
                self.create_start_btn(groupName,'32442')
            elif isSNInput == 3:
                pass
        except ValueError as e:
            print("SNInput is not defined")
            
        finally:
            pass
                

    def receiveTable(self,table):
        self.table = table

    def create_start_btn(self,label,sn):
        # print("you need to click start button")
        container = ScrolledFrame(self)
        container.pack(fill=BOTH, expand=YES)
        
        self.buttons = []
        self.logButtons = []
        for x in range(self.count):
            lbl = ttk.Label(master=container, text=label+str(x), width=6, bootstyle=WARNING)
            lbl.grid(row=x,column=0,padx=2,pady=5)

            self.buttons.append(
                ttk.Button(
                    master=container,
                    text="Start",
                    # command=lambda: self.startNoSN(sn,x),
                    command=partial(self.startNoSN, sn, x),
                    bootstyle=INFO,
                    width=5,
                    state=NORMAL
                )
            )
            self.logButtons.append(
                ttk.Button(
                    master=container,
                    text="HM32434NBNF332",
                    # command=lambda: self.startNoSN(sn,x),
                    command=partial(self.openLogFile, sn, x),
                    bootstyle=LIGHT,
                    width=10,
                    state=DISABLED
                )
                # ttk.Label(master=container, text="HM32434NBNF332", width=10, bootstyle=DARK)
            ) 
        for index, sub_btn in enumerate(self.buttons):
            sub_btn.grid(row=index,column=1,padx=5,pady=5)
            # sub_btn.bind('<Button-1>', self.startNoSN) 
        for index, btn in enumerate(self.logButtons):
            btn.grid(row=index,column=2,padx=2,pady=5)
    
    def startTest(self,x):
        Main.main({"groupIndex":x,"tableTree":self.tableTree})
        

    # start按钮点击事件（无扫码框）
    def startNoSN(self,sn,x):
        
        print("startNoSn")
        print("startNoSN Value---",x)
        self.ListenTestStartedCallback(x)
        # self.testFinishedCallBack(x,True)
        # Main.initMain(x)#开始测试，开辟多线程执行
        # tableTreeP = None
        # if x == 0:
        print(self.cbo.get())

        # print(self.selectIndex)
        # print(x)
        # print("pppppppppppppppppppppppp")
        if int(self.cbo.get()) == int(x):
            print("进来了")
            self.tableTree.delete(*self.tableTree.get_children())

        tableTreeP = self.tableTree
        self.urlArr = varConfig().urlArr
        
      
        thread = Thread(target=Main.main,args=({"groupIndex":x,"tableTree":tableTreeP,"dataArray":self.dataArray,"groupArray":self.groupArray,"resultArray":self.resultArray,"enterEL":self,"urls":self.urlArr},),name=str(x))
        thread.setDaemon(True)
        thread.start()
    
        
        
    def openLogFile(self,sn,x):
        print("openLogFile x---",x)

        
    # ----------------分割线----Start--------------------
    # 测试开始回调
    def testStartedCallBack(self,groupIndex):
        # print("----back group: ",groupIndex)
        config = stationConfig.stationConfig()
        if config.SNInput == 2 :#only start button
            button = self.buttons[groupIndex]                   
            button.configure(bootstyle=WARNING,text = "Testing",state=DISABLED)
            logButton = self.logButtons[groupIndex]
            logButton.configure(bootstyle=LIGHT,text = "loading......",state=NORMAL)
            
        elif config.SNInput == 1:  # scansn entry
            # button = self.snBtns[groupIndex]
            # button.configure(bootstyle=WARNING,text = "Testing",state=DISABLED)
            
            entry = self.snEntrys[groupIndex]
            entry.config(state = DISABLED)
            
            print('state:',self.snEntrys[groupIndex+1].state())


            self.snEntrys[groupIndex+1].focus_set()
            snlogButton = self.snLogButtons[groupIndex]
            snlogButton.configure(bootstyle=LIGHT,text = "Testing",state=NORMAL)
            
        
    # api 监听测试开始的group
    def ListenTestStartedCallback(self,groupIndex):
        
        self.testStartedCallBack(groupIndex)

    # ----------------分割线---sn---------------------

    # 关于sn的回调函数 
    def snCallBack(self,groupIndex,sn):
        print("----back: ",sn)
        lab = self.labs[groupIndex]
        lab.configure(bootstyle=INFO, text=str(sn))

    # api 监听sn变化
    def winSNCallback(self,groupIndex,sn):
        self.snCallBack(groupIndex,sn)
    # ----------------分割线-------Finish-----------------
    # 测试结束回调
    def testFinishedCallBack(self,groupIndex,result):
        print("----back group: ",groupIndex)
        print("----back result: ",result)
        config = stationConfig.stationConfig()
        if config.SNInput == 2 :
            button = self.buttons[groupIndex]
            button.configure(bootstyle=INFO,text = "HM6J10TD18JQ",state=NORMAL)
            logButton = self.logButtons[groupIndex]
            if result:
                
                logButton.configure(bootstyle=SUCCESS,text = "HM6J10TD18JQ",state=NORMAL)
                
            else:
                
                logButton.configure(bootstyle=DANGER,text = "HM6J10TD18JQ",state=NORMAL)
        elif config.SNInput == 1:

            self.snTable[groupIndex].set("")
            entry = self.snEntrys[groupIndex]
            entry.config(state = NORMAL)

            snlogButton = self.snLogButtons[groupIndex]
            if result:
        
                
                snlogButton.configure(bootstyle=SUCCESS,text = "1234567890",state=NORMAL)
            else:
                
                snlogButton.configure(bootstyle=DANGER,text = "HM6J10TD18JQ",state=NORMAL)
                    

    # api 监听测试结果
    def ListenTestResultCallback(self,groupIndex,result):
        log().TestFinishCreateArchiveLog("HM11111")
        self.testFinishedCallBack(groupIndex,result)

    # ----------------分割线------------------------
    
    # 扫码框UI构建
    def create_form_entry(self, label, variable):
        """Create a single form entry"""
        container = ScrolledFrame(self)
        container.pack(fill=BOTH, expand=YES)

        self.snEntrys = []
        # self.snBtns = []  
        self.snLogButtons = []      

        for x in range(self.count):
            
            lbl = ttk.Label(master=container, text=label+str(x), width=6, bootstyle=PRIMARY)
            lbl.grid(row=x,column=0,padx=2,pady=5)

            self.snEntrys.append(
                ttk.Entry(master=container, textvariable=variable[x], width=5)
            )
            
            # self.snBtns.append(
            #     ttk.Button(
            #         master=container,
            #         text="HM6J10TD18JQ",
            #         command=self.on_start,
            #         bootstyle=SUCCESS,
            #         width=4,
            #     )
            # )

            # sn
            self.snLogButtons.append(
                ttk.Button(
                    master=container,
                    text="HM6J10TD18JQ",
                    command=partial(self.openSNLogFileAction, x),
                    bootstyle=SUCCESS,
                    width=15
                )
            )
        
        for index, entry in enumerate(self.snEntrys):
            entry.grid(row=index,column=1,padx=5,pady=5)
            # entry.bind("<Return>", lambda event:self.on_start_Event(event, index))
            entry.bind('<Return>', self.handler_adaptor(self.on_start_Event, x=index))  # 右键双击
            if index == 0:
                # first responder
                entry.focus_set()
            
        # for index, btn in enumerate(self.snBtns):
        #     btn.grid(row=index,column=2,padx=5,pady=5)

        for index, snLogButton in enumerate(self.snLogButtons):
            snLogButton.grid(row=index,column=2,padx=5,pady=5)	

    # 中介函数
    def handler_adaptor(self,fun, **kwds):
        return lambda event, fun=fun, kwds=kwds: fun(event, **kwds)

    def on_start(self):
        """Print the contents to console and return the values."""
        print("Name:", self.sn.get())
        return self.sn.get()
    
    # 输入框的触发事件
    def on_start_Event(self,event,x):
        print("zhqzhqzhq========")
        s = event.keysym
        sn = self.snTable[x].get()
        print("index----",x)
        print("sn----",sn)
        # self.on_start()
        # self.keyboard.tap_key('Tab', n=2, interval=0) 	 
        # Main.initMain(x)
        
        # old
        # Main.main({"groupIndex":x})
        tableTreeP = self.tableTree
        self.urlArr = varConfig().urlArr
        
        
        
        thread = Thread(target=Main.main,args=({"groupIndex":x,"tableTree":tableTreeP,"dataArray":self.dataArray,"groupArray":self.groupArray,"resultArray":self.resultArray,"enterEL":self,"urls":self.urlArr},),name=str(x))
        thread.setDaemon(True)
        thread.start()
        
        self.testStartedCallBack(x)
        
    def on_reset(self,x):
        # self.sn = ttk.StringVar(value="")
        # self.sn.set("")
        self.snTable[x].set()

    def openSNLogFileAction(self,x):
        print("open scan sn log")
        sn = self.snTable[x].get()
        # test
        self.testFinishedCallBack(x,False)
        

if __name__ == "__main__":

    app = ttk.Window("Data Entry", "flatly", resizable=(True, True))
    app.geometry('600x200+30+20')
    app.config(background="red")
    DataEntryForm(app,0,"group")
    # DataEntryForm(app,"noScanSN","group")
    app.mainloop()
